package com.zt.ztyh.admin.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.sun.jdi.InternalException;
import com.zt.ztyh.admin.config.MinioProperties;
import com.zt.ztyh.admin.service.FileUploadService;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.XmlParserException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.rmi.ServerException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Resource
    private MinioProperties minioProperties;
    @Override
    public String fileUpload(MultipartFile file) throws ServerException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InternalException, io.minio.errors.ServerException, InsufficientDataException, io.minio.errors.ErrorResponseException, InvalidResponseException, XmlParserException, io.minio.errors.InternalException {
        //创建一个minio的客户端对象
        MinioClient minioClient= MinioClient.builder()
                .endpoint(minioProperties.getEndpointUrl())
                .credentials(minioProperties.getAccessKey(),minioProperties.getSecreKey())
                .build();
        //判断桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if(!found){
            //如果不存在，那么此时就创建一个新的桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        }else{
            //如果存在则打印信息
            System.out.println("Bucket 'ztzx-bucket' alread exists");
        }
        //设置存储对象名称
        String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //获取文件名称
        String fileName = dateDir+"/"+uuid+file.getOriginalFilename();
        System.out.println(fileName);
        PutObjectArgs putObjectArgs= PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .stream(file.getInputStream(), file.getSize(),-1)
                .object(fileName)
                .build();
        minioClient.putObject(putObjectArgs);
        return minioProperties.getEndpointUrl()+"/"+minioProperties.getBucketName()+"/"+fileName;
    }
}
